<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2023/9/21
 * Time: 14:58
 */

namespace app\admin\service;

use Carbon\Carbon;
use Exception;
use lib\common\CommonService;
use lib\exception\AuthException;
use lib\exception\FailureException;
use model\AdminPermissionModel;
use model\AdminPermissionUserModel;
use model\AdminUserModel;
use Tinywan\Jwt\JwtToken;

class AuthService extends CommonService
{
    private AdminUserModel $adminUserModel;
    private AdminPermissionUserModel $adminPermissionUserModel;

    private MenuService $menuService;

    /**
     * @param AdminUserModel $adminUserModel
     * @param AdminPermissionUserModel $adminPermissionUserModel
     * @param MenuService $menuService
     */
    public function __construct (AdminUserModel $adminUserModel, AdminPermissionUserModel $adminPermissionUserModel, MenuService $menuService) {
        parent::__construct();
        $this->adminUserModel = $adminUserModel;
        $this->adminPermissionUserModel = $adminPermissionUserModel;
        $this->menuService = $menuService;
    }


    public function login ($params): array {
        $user = $this->adminUserModel->getLoginUser($params['username']);
        if (empty($user)) {
            throw new FailureException('账号密码不匹配');
        }
        if ($user['status'] != 1) {
            throw new FailureException('账号异常, 请联系管理员');
        }
        if (!password_verify($params['password'], $user['password'])) {
            throw new FailureException('账号密码不匹配');
        }
        $user->save(['login_time' => Carbon::now()->toDateTimeString(), 'login_ip' => request()->getRealIp()]);
        return JwtToken::generateToken(['id' => $user['id']]);
    }

    public function refreshToken () {
        try {
            $data = JwtToken::refreshToken();
        } catch (Exception $e) {
            throw new AuthException();
        }
        return $data;
    }

    public function userinfo (AdminUserModel $user): AdminUserModel {
        $permissions = $this->adminPermissionUserModel->getUserPermission($user['id']);
        $permissionIds = array_column($permissions, 'id');
        $user['menus'] = $this->menuService->permissionMenuList($permissionIds);
        $user['permissions'] = $permissions;
        return $user;
    }

}
